package com.linked.scheduledtasks.service;


import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.linked.scheduledtasks.bean.po.SwitchInfoPO;
import com.linked.scheduledtasks.feign.IBaseManageFeign;
import com.linked.universal.common.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author :dbq
 * @date : 2022/11/24 9:52
 */
@Service
public class SwitchService {

    private final static Logger logger = LoggerFactory.getLogger(SwitchService.class);

    private final IBaseManageFeign baseManageFeign;

    private final static String DELAYEDSWITCH = "DelayedSwitch";

    private final static String AUTOSWITCH = "AutoSwitch";

    private final RedisTemplate redisTemplate;

    @Autowired
    private ObjectMapper mapper;

    @Autowired
    public SwitchService(IBaseManageFeign baseManageFeign, RedisTemplate redisTemplate) {
        this.baseManageFeign = baseManageFeign;
        this.redisTemplate = redisTemplate;
    }

    public void delayedSwitch() throws Exception {
        /**
         * 拿取对应开关列表
         * */
        List<SwitchInfoPO> switchLIst = null;
        if (redisTemplate.hasKey(DELAYEDSWITCH)) {
            String jsonStr = (String) redisTemplate.opsForValue().get(DELAYEDSWITCH);
            switchLIst = mapper.readValue(jsonStr, new TypeReference<List<SwitchInfoPO>>() {
            });

        } else {
            SwitchInfoPO param = new SwitchInfoPO();
            param.setIfTime(2);
            Result ret = baseManageFeign.querySwitchList(param);
            switchLIst = (List<SwitchInfoPO>) ret.get("data");
            redisTemplate.opsForValue().set(DELAYEDSWITCH, mapper.writeValueAsString(switchLIst), 24, TimeUnit.HOURS);
        }

        /**
         * 时间判断
         * */
        LocalDateTime current = LocalDateTime.now();
        List<SwitchInfoPO> doSwitchs = new ArrayList<>();
        Boolean ret = false;
        for (SwitchInfoPO index : switchLIst) {
            if (current.isBefore(index.getDelayedTime())) {
                SwitchInfoPO temp = new SwitchInfoPO();
                temp.setSwitchId(index.getSwitchId());
                temp.setIfTime(0);
                temp.setIfSwitch(!index.getIfSwitch());
                temp.setDelayedTime(null);
                baseManageFeign.updateSwitchInfo(temp);
                ret = true;
            }
        }
        if (ret) {
            redisTemplate.delete(DELAYEDSWITCH);
        }
    }

    public void autoSwitch() throws Exception {
        /**
         * 拿取对应开关列表
         * */
        List<SwitchInfoPO> switchLIst = null;
        if (redisTemplate.hasKey(AUTOSWITCH)) {
            String jsonStr = (String) redisTemplate.opsForValue().get(AUTOSWITCH);
            //switchLIst = JSON.parseArray(jsonStr, SwitchInfoPO.class);
            switchLIst = mapper.readValue(jsonStr, new TypeReference<List<SwitchInfoPO>>(){});
        } else {
            SwitchInfoPO param = new SwitchInfoPO();
            param.setIfTime(1);
            Result ret = baseManageFeign.querySwitchList(param);
            if ((Boolean) ret.get("success")) {
                switchLIst = (List<SwitchInfoPO>) ret.get("data");
                redisTemplate.opsForValue().set(AUTOSWITCH, mapper.writeValueAsString(switchLIst), 24, TimeUnit.HOURS);
            } else {
                logger.error("查询不到开关列表！");
                return;
            }
        }
        if (logger.isInfoEnabled()) {
            logger.info("数据：" + mapper.writeValueAsString(switchLIst));
        }
        /**
         * 时间判断
         * */
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm");
        String time = formatter.format(LocalDateTime.now());
        if (logger.isInfoEnabled()) {
            logger.info("当前时间：" + time);
        }

        List<String> onSwitchs_string = new ArrayList<>();
        List<String> offSwitchs_string = new ArrayList<>();
        for (SwitchInfoPO index : switchLIst) {
            if (time.equals(index.getOnTime())) {
                onSwitchs_string.add(index.getSwitchId());
            }
            if (time.equals(index.getOffTime())) {
                offSwitchs_string.add(index.getSwitchId());
            }
        }
        if (logger.isInfoEnabled()) {
            logger.info("定时启动开关列表：" + mapper.writeValueAsString(onSwitchs_string));
            logger.info("定时关闭开关列表：" + mapper.writeValueAsString(offSwitchs_string));
        }
        /**
         * 调用修改开关方法
         * */
        if (!CollectionUtils.isEmpty(onSwitchs_string)) {
            for (String index : onSwitchs_string) {
                logger.info("开关名称：" + index);
                SwitchInfoPO temp = new SwitchInfoPO();
                temp.setSwitchId(index);
                temp.setIfSwitch(true);
                Boolean ret = baseManageFeign.updateSwitchInfo(temp);
            }
        }
        if (!CollectionUtils.isEmpty(offSwitchs_string)) {
            for (String index : offSwitchs_string) {
                logger.info("开关名称：" + index);
                SwitchInfoPO temp = new SwitchInfoPO();
                temp.setSwitchId(index);
                temp.setIfSwitch(false);
                Boolean ret = baseManageFeign.updateSwitchInfo(temp);
            }
        }
    }
}
